﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LinkCard.Model;
using LinkCard.Dao;
using LinkCard.AdminCP.Common;
using System.Data;

namespace LinkCard.AdminCP.CRM
{
    public partial class customers_edit : System.Web.UI.Page
    {
        protected bool nInTemp;

        protected void Page_Load(object sender, EventArgs e)
        {

            if (Session["USER"] == null)
            {
                Response.Redirect("/login.aspx");
            }

            if (!IsPostBack)
            {
                Int64 nCustomerID = ConvertUtility.ToInt64(Request.QueryString["CustomerID"]);
                CustomerID.Value = nCustomerID.ToString();
                if (nCustomerID > 0)
                {
                    btnUpdate.Visible = false;
                    btnPublish.Visible = false;
                    btnDel.Visible = false;
                    btnAccept.Visible = false;
                    btnDrop.Visible = false;

                    string sSQL = "";
                    nInTemp = inTemp(nCustomerID);
                    if (nInTemp) //khách hàng đăng kí qua admincp sẽ lưu thêm trong Temp
                    {
                        sSQL = "SELECT * FROM CustomerTemp WHERE CustomerID =" + nCustomerID.ToString() + "";
                        btnAccept.Visible = true;
                        btnDrop.Visible = true;

                    }
                    else //khách hàng đăng kí qua web sẽ không vô bảng Temp
                    {
                        sSQL = "SELECT * FROM Customer WHERE CustomerID =" + nCustomerID.ToString() + "";
                        btnPublish.Visible = true;
                        btnDel.Visible = true;

                    }

                    DataTable dtCustomer = DataHelper.SelectTable(sSQL, false);
                    if (dtCustomer.Rows.Count > 0)
                    {

                        Address.Value = dtCustomer.Rows[0]["Address"].ToString();

                        Birthday.Value = dtCustomer.Rows[0]["Birthday"].ToString();

                        Email.Value = dtCustomer.Rows[0]["Email"].ToString();

                        Fullname.Value = dtCustomer.Rows[0]["Fullname"].ToString();
                        
                        CardNumber.Value = dtCustomer.Rows[0]["CardNumber"].ToString();

                        Gender.SelectedIndex = ConvertUtility.ToInt32( dtCustomer.Rows[0]["Gender"]);

                        ID.Value = dtCustomer.Rows[0]["ID"].ToString();

                        Income.Value = dtCustomer.Rows[0]["Income"].ToString();

                        Job.Value = dtCustomer.Rows[0]["Job"].ToString();

                        MobilePhone.Value = dtCustomer.Rows[0]["MobilePhone"].ToString();

                        OtherInfo.Value = dtCustomer.Rows[0]["OtherInfo"].ToString();

                        Point.Value = dtCustomer.Rows[0]["Point"].ToString();

                        SystemRegister.SelectedIndex = ConvertUtility.ToInt32(dtCustomer.Rows[0]["SystemRegister"]);

                        TransactionAmount.Value = dtCustomer.Rows[0]["TransactionAmount"].ToString();

                        Status.Value = dtCustomer.Rows[0]["Status"].ToString();

                        VietnamAirlineGLPNumber.Value = dtCustomer.Rows[0]["VietnamAirlineGLPNumber"].ToString();

                        object exDate = dtCustomer.Rows[0]["ExpiredDate"];

                        if (exDate == DBNull.Value)
                        {
                            ckNoExpiredDate.Checked = true;
                        }
                        else
                        {
                            var exTemp = Convert.ToDateTime(dtCustomer.Rows[0]["ExpiredDate"].ToString());
                            ExpiredDate.Value = exTemp.Day.ToString() + "/" + exTemp.Month.ToString() + "/" + exTemp.Year.ToString();
                        }
                        

                        Password.Value = Utils.EncryptPass.Decrypt(dtCustomer.Rows[0]["Password"].ToString(), CardNumber.Value);

                        //Password.Value = dtCustomer.Rows[0]["Password"].ToString();

                        if (ConvertUtility.ToByte(dtCustomer.Rows[0]["Status"].ToString()) == 0) btnUpdate.Visible = true;

                    }
                }
            }

        }

        //Kiểm tra xem có trong bảng Temp không. 
        //Nếu đăng kí qua AdminCP thì sẽ có
        //Nếu đăng kí qua web thì không có
        protected bool inTemp(Int64 nCustomerID)
        {

            DataTable dtCustomerTemp = DataHelper.SelectTable("SELECT CustomerID FROM CustomerTemp WHERE CustomerID =" + nCustomerID.ToString() + "", false);
            if (dtCustomerTemp.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        protected Int64 getUserID()
        {

            DataTable dt = DataHelper.SelectTable("SELECT UserID FROM [User] WHERE Username ='" + Session["USER"].ToString() + "'", false);
            if (dt.Rows.Count > 0)
            {
                return ConvertUtility.ToInt64(dt.Rows[0]["UserID"]);
            }
            else
            {
                return 0;
            }
        }

        protected void btnPublish_Click(object sender, EventArgs e)
        {
            addCustomerTemp(getUserID());
            if (ConvertUtility.ToByte(Status.Value) == 2)
            {
                Response.Redirect("/CRM/customers_all_published.aspx");
            }
            else
            {
                updateCustomer(1);
                Response.Redirect("/CRM/customers_list.aspx");
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            updateCustomer(0);

            Response.Redirect("/CRM/customers_list.aspx");

        }

        protected void btnDel_Click(object sender, EventArgs e)
        {
            string sSQL = "delete customer where CustomerID = " + CustomerID.Value; ;
            DataHelper.ExecuteNonQuery(sSQL, true);
            if (ConvertUtility.ToByte(Status.Value) == 2)
            {
                Response.Redirect("/CRM/customers_all_published.aspx");
            }
            else
            {
                Response.Redirect("/CRM/customers_list.aspx");
            }
        }

        protected void btnAccept_Click(object sender, EventArgs e)
        {
            updateCustomer(2);
            // Xóa Temp
            string sSQL = "delete CustomerTemp where CustomerID = " + CustomerID.Value; ;
            DataHelper.ExecuteNonQuery(sSQL, true);
            Response.Redirect("/CRM/customers_all_pending.aspx");
        }

        protected void btnDrop_Click(object sender, EventArgs e)
        {
            string sSQL = "delete CustomerTemp where CustomerID = " + CustomerID.Value; ;
            DataHelper.ExecuteNonQuery(sSQL, true);
            Response.Redirect("/CRM/customers_all_pending.aspx");
        }

        protected void updateCustomer(byte status)
        {
            System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo();
            dateInfo.ShortDatePattern = "dd/MM/yyyy";

            var dao = new CustomerDao();

            var _cus = new Customer();
            _cus.CustomerID = ConvertUtility.ToInt64(CustomerID.Value);
            _cus.CardNumber = CardNumber.Value;
            _cus.Address = Address.Value;
            
            if (Birthday.Value != "")
                _cus.Birthday = ConvertUtility.ToDateTime(Birthday.Value);

            _cus.Email = Email.Value;
            _cus.Fullname = Fullname.Value;
            _cus.Gender = Convert.ToByte(Gender.SelectedItem.Value);
            _cus.ID = ID.Value;
            _cus.Income = ConvertUtility.ToDecimal(Income.Value);
            _cus.Job = Job.Value;
            _cus.MobilePhone = MobilePhone.Value;
            _cus.OtherInfo = OtherInfo.Value;
            _cus.Point = ConvertUtility.ToInt32(Point.Value);
            _cus.SystemRegister = Convert.ToByte(SystemRegister.SelectedItem.Value);
            _cus.TransactionAmount = ConvertUtility.ToDecimal(TransactionAmount.Value);
            _cus.Status = status;
            //_cus.Tags = txtTags.Value;
            _cus.VietnamAirlineGLPNumber = VietnamAirlineGLPNumber.Value;
            if (!ckNoExpiredDate.Checked)
            {
                if (ExpiredDate.Value != "")
                    _cus.ExpiredDate = Convert.ToDateTime(ExpiredDate.Value, dateInfo);

            }
            //_cus.CardLevel = Convert.ToByte(CardLevel.Value);

            if (status == 2) // chỉ send sms khi đã duyệt
            {
                _cus.IsActive = true;
            }

            dao.Update(_cus);

            //if (!string.IsNullOrEmpty(_cus.Tags))
            //{
            //    var addTag = new TagDao().AddDealTag(_cus.CustomerID, _cus.Tags);
            //}

            if (status == 2) // chỉ send sms khi đã duyệt
            {
                if ((MobilePhone.Value.Trim() != "") && MobilePhone.Value.Trim().Length >= 10)
                {
                    Int64 _kqSMS = Utils.SMSTool.SendSMS(MobilePhone.Value.Trim(), "Cam on Khach hang da su dung dich vu cua LinkCard. Tai khoan cua quy khach da duoc active");
                    if (_kqSMS < 0) //nếu nhắn tin lỗi thì log lại lỗi, nhắn ok thì thôi ko lưu lại nữa
                    {
                        var logSMS = Utils.LogActions.LogItem(0, 0, 0, ConvertUtility.ToInt64(CustomerID.Value), 0, "Lỗi nhắn tin: " + _kqSMS.ToString(), "Create Customer", "AdminCP");
                    }
                }
            }

        }

        protected void addCustomerTemp(Int64 nUserID)
        {
            System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo();
            dateInfo.ShortDatePattern = "dd/MM/yyyy";

            var dao = new CustomerTempDao();

            var _cus = new CustomerTemp();
            _cus.CustomerID = ConvertUtility.ToInt64(CustomerID.Value);
            //_cus.Username = Username.Value;
            _cus.CardNumber = CardNumber.Value;
            _cus.Address = Address.Value;

            if (Birthday.Value != "")
                _cus.Birthday = ConvertUtility.ToDateTime(Birthday.Value);
            
            _cus.Email = Email.Value;
            _cus.Fullname = Fullname.Value;
            _cus.Gender = ConvertUtility.ToByte(Gender.SelectedItem.Value);
            _cus.ID = ID.Value;
            _cus.Income = ConvertUtility.ToDecimal(Income.Value);
            _cus.Job = Job.Value;
            _cus.MobilePhone = MobilePhone.Value;
            _cus.OtherInfo = OtherInfo.Value;
            _cus.Point = ConvertUtility.ToInt32(Point.Value);
            _cus.SystemRegister = Convert.ToByte(SystemRegister.SelectedItem.Value);
            _cus.TransactionAmount = ConvertUtility.ToDecimal(TransactionAmount.Value);
            _cus.UserID = nUserID;
            _cus.Status = 1;
            _cus.DateLog = DateTime.Now;
            _cus.VietnamAirlineGLPNumber = VietnamAirlineGLPNumber.Value;
            if (!ckNoExpiredDate.Checked)
            {
                if (ExpiredDate.Value != "")
                    _cus.ExpiredDate = Convert.ToDateTime(ExpiredDate.Value, dateInfo);
            }
            //_cus.CardLevel = Convert.ToByte(CardLevel.Value);

            dao.Add(_cus);


        }
    }
}